//
//  GXWhereViewController.swift
//  BallGame
//
//  Created by GuangXiao on 16/3/17.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class GXWhereViewController: UIViewController,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate{

//    @IBOutlet weak var _mapView: BMKMapView!
    
    var _mapView:BMKMapView?
    /// 定位服务工具类
    var _locService:BMKLocationService?
    /// 反地理编码工具类
    var _geocodeSearch: BMKGeoCodeSearch!

    override func viewDidLoad() {
        super.viewDidLoad()

        //创建添加mapView
        _mapView = BMKMapView(frame: CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height))
        //设置mapView的缩放等级
        _mapView?.zoomLevel = 16
        view.addSubview(_mapView!)

        
        _geocodeSearch = BMKGeoCodeSearch()

        //创建开启定位服务
        _locService = BMKLocationService()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        _mapView?.viewWillAppear()
        //设置代理
        _mapView?.delegate = self
        _locService?.delegate = self
        _geocodeSearch?.delegate = self
        

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        _locService?.startUserLocationService()
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        _mapView?.viewWillDisappear()
        //置空代理
        _mapView?.delegate = nil
        _locService?.delegate = nil
        _geocodeSearch.delegate = nil
    }
    
    //MARK: - BMKLocationServiceDelegate
    
    /**
    *用户位置更新后，会调用此函数
    *@param userLocation 新的用户位置
    */
    func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {

        NSLog("didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
        //创建大头针 并设定大头针位置
        let annotation:BMKPointAnnotation = BMKPointAnnotation()
        annotation.coordinate = userLocation.location.coordinate
        //将大头针添加的mapView上
        _mapView?.addAnnotation(annotation)
        
        //将定位的位置 设置为地图的中心点
        self._mapView?.setCenterCoordinate(annotation.coordinate, animated: true)
        
        reverseGeoSearch(annotation.coordinate)
        //停止定位
        _locService?.stopUserLocationService()
    }
    
    
    /**
    *定位失败后，会调用此函数
    *@param error 错误号
    */
    func didFailToLocateUserWithError(error: NSError!) {
        print("定位失败，error:\(error)")
        //如果定位失败 重新启动定位方法
        _locService?.startUserLocationService()
    }
    
    
    //MARK: - MapViewDelegate
    
    //添加annotation是会调用
    func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! {
        let AnnotationViewID = "renameMark"
        var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! BMKPinAnnotationView?
        if annotationView == nil {
            annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
            // 设置颜色
            annotationView!.pinColor = UInt(BMKPinAnnotationColorRed)
            // 从天上掉下的动画
            annotationView!.animatesDrop = true
            
            //设置自定义的图片
            annotationView?.image = UIImage(named:"大头针.png")
            
            // 设置是否可以拖拽
            annotationView!.draggable = false
        }
        annotationView?.annotation = annotation
        return annotationView
    }

    
    
     //MARK: - BMKGeoCodeSearchDelegate
    /**
    *返回反地理编码搜索结果
    *@param searcher 搜索对象
    *@param result 搜索结果
    *@param error 错误号，@see BMKSearchErrorCode
    */
    func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        if error == BMK_SEARCH_NO_ERROR {
            //弹框提示当前位置
            let alertView = UIAlertController(title: "您现在的位置是", message: result.address, preferredStyle: .Alert)
            let okAction = UIAlertAction(title: "我知道了", style: .Default, handler: nil)
            alertView.addAction(okAction)
            self.presentViewController(alertView, animated: true, completion: nil)
        }
    }
    
     //MARK: - 自定义反地理编码方法
    /**
     反地理编码方法
     
     - parameter coordinate: 经纬度
     */
    func reverseGeoSearch(coordinate:CLLocationCoordinate2D) {
        
        /// 反地理编码检索信息类
        let reverseGeocodeSearchOption = BMKReverseGeoCodeOption()
        
        reverseGeocodeSearchOption.reverseGeoPoint = coordinate
        
        let flag = _geocodeSearch.reverseGeoCode(reverseGeocodeSearchOption)
        if flag {
            print("反geo 检索发送成功")
        } else {
            print("反geo 检索发送失败")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    
}
